import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Button, Select, Modal, message, Form, Input } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { cachetaskEdit, cachetaskSearch } from '@/services/server';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';
import { EnumCacheKey } from '@/utils/constant';

import styles from './style.less';

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [modalNumForm] = Form.useForm();
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelNumVisible, setModelNumVisible] = useState<boolean>(false);

  const getEnumCacheKey = () => {
    const obj = {};
    EnumCacheKey.forEach((item) => {
      obj[item.label] = {
        text: item.label,
      };
    });
    return obj;
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '账号',
      dataIndex: 'updateUser',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: 'key选择',
      dataIndex: 'cacheKey',
      hideInTable: true,
      fieldProps: {
        placeholder: '请选择',
      },
      valueEnum: getEnumCacheKey(),
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      valueType: 'date',
      hideInTable: true,
      fieldProps: {
        placeholder: '开始时间',
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
      },
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      valueType: 'date',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
      },
    },
    // 表格
    {
      title: 'key类型',
      dataIndex: 'cacheKey',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '缓存值',
      dataIndex: 'cacheValue',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '最后更新时间',
      dataIndex: 'lastUpdateTime',
      ellipsis: true,
      width: 190,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '账号',
      dataIndex: 'updateUser',
      ellipsis: true,
      width: 160,
      align: 'center',
      hideInSearch: true,
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await cachetaskSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleNumCancel = () => {
    setModelNumVisible(false);
    modalNumForm.resetFields();
  };

  const handleNumOK = () => {
    modalNumForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const { code, data } = await cachetaskEdit({ ...values });
      if (code === 200) {
        message.success('操作成功');
        modalNumForm.resetFields();
        setModelNumVisible(false);
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
    });
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.CodegroupListItem>
          manualRequest={true}
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button type="primary" key="add" onClick={() => setModelNumVisible(true)}>
              新增
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />
        <Modal
          title="新增"
          width={520}
          open={modelNumVisible}
          onOk={handleNumOK}
          onCancel={handleNumCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalNumForm}
            initialValues={{
              cacheKey: '',
              cacheValue: '',
            }}
          >
            <Form.Item
              label="key类型"
              name="cacheKey"
              style={{ width: 400 }}
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Select options={EnumCacheKey} />
            </Form.Item>
            <Form.Item label="缓存值" name="cacheValue" style={{ width: 400 }}>
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
